package com.cet.designpatterns.prototype.深拷贝;

import java.io.*;

/**
 * @program: algorithm
 * @description:
 * @author: 陈恩涛
 * @create: 2021-09-06 16:21
 **/
public class DeepProtoType implements Serializable, Cloneable {

    private static final long serialVersionUID = -1289301926038553940L;

    /**
     * 不可变属性
     */
    private String name;

    /**
     * 引用类型属性
     */
    private DeepCloneableTarget target;

    public DeepProtoType() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DeepCloneableTarget getTarget() {
        return target;
    }

    public void setTarget(DeepCloneableTarget target) {
        this.target = target;
    }

    //深拷贝 - 方式1：使用clone方法

    @Override
    protected Object clone() throws CloneNotSupportedException {
        Object deep = null;
        //这里完成对基本数据类型和不可变类型属性的克隆
        deep = super.clone();
        //对引用类型的属性进行单独的处理
        DeepProtoType deepProtoType = (DeepProtoType) deep;
        deepProtoType.setTarget((DeepCloneableTarget) target.clone());
        return deep;
    }

    //深拷贝 - 方式2通过对象的序列化实现（推荐）
    public Object deepClone() {
        //创建流对象
        ByteArrayOutputStream bos = null;
        ObjectOutputStream oos = null;
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;

        try {
            //序列化
            bos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(bos);
            //当前这个对象以对象流的方式输出
            oos.writeObject(this);

            //反序列化
            bis = new ByteArrayInputStream(bos.toByteArray());
            ois = new ObjectInputStream(bis);
            DeepProtoType copyObj = (DeepProtoType) ois.readObject();
            return copyObj;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //关闭流
            try {
                bos.close();
                oos.close();
                bis.close();
                ois.close();
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
